<?php

namespace App\Controllers;

use Windward\Core\Response\Plain as PlainResponse;

class User extends Base
{

    public $model = null;

    public function __construct(\Windward\Core\Container $container)
    {
        parent::__construct($container);
        $this->model = $container->model('User');
    }

    /**
     * 用户个人信息
     */
    public function indexAction()
    {
        //推荐者用户ID
        $refererId = $this->request->getQuery('referer_id');
        $this->container->set('referer_id', $refererId);
        setcookie('referer_id_' . $this->club['id'], $refererId, time() + 3600 * 24 * 365);
        $mobile = $_COOKIE['user_mobile_' . $this->club['id']];
        $aes = new \Windward\Lib\Aes();
        $mobile = $aes->decrypt($mobile, $this->codeConfig['aesKey'], $this->codeConfig['aesIv']);
        if (!$mobile || !preg_match('/^1[0-9]{10}$/', $mobile)) {
            $this->redirect('/user/mobileLogin');
        }
        $_SESSION['club_mobile'] = $mobile;
        $clubUser = $this->model->getUserByMobile($mobile);
        if ($clubUser) {
            $_SESSION['club_user'] = $clubUser;
        }
        $response = new \Windward\Core\Response\Smarty($this->container);
        switch ($clubUser['auth_status']) {
            case 0://未认证
                $authitemModel = $this->container->model('Authitem');
                $authitem = $authitemModel->getAuthitem($this->club['id']);
                foreach ($authitem as &$val) {
                    array_walk($val, function (&$item) {
                        if ($item['item_type'] == 4) {
                            $item['item_val_list'] = explode(',', $item['item_val']);
                        }
                    });
                }
                $brand = $this->model->get('tb_car_brand', 'id,name', ['deleted' => 0], false);
                $model = $this->model->get('tb_car_model', 'id,name,brand_id', ['deleted' => 0], false);
                $response->set('authitem', $authitem);
                $response->set('user', $clubUser);
                $response->set('brand', $brand);
                $response->set('model', $model);
                $response->set('mobile', $mobile);
                $response->setTpl("User/input");
                $response->set('title', '车友认证');
                break;
            case 1://审核中
                $this->redirect('/user/profile');
                break;
            case 2://已认证
                $user = $_SESSION['club_user'];
                $response->set('user', $user);
                $response->setTpl("User/center");
                $response->set('title', '个人中心');
                break;
            case 3://认证失败
                $user = $_SESSION['club_user'];
                $this->redirect('/user/input?auth_status=' . $user['auth_status']);
                break;
            default:
                break;
        }
        return $response;
    }

    /**
     * 填写个人认证信息
     */
    public function inputAction()
    {
        $authStatus = $this->request->getQuery('auth_status');
        $data = $this->request->getPost('data');
        $authitemModel = $this->container->model('Authitem');
        $authitem = $authitemModel->getAuthitem($this->club['id']);
        $errors = [];
        $mobile = $_SESSION['club_mobile'];
        $user = $this->model->getUserByMobile($_SESSION['club_mobile']);
        if ($user && $user['auth_status'] != 0){
            $this->redirect('/user/index');
        }
        if ($authStatus != 3) {
            if ($this->request->isComplete()) {
                if ($this->model->validInput($data, $authitem, $errors)) {
                    $res = $this->model->saveAuth($data);
                    if ($res === false) {
                        $errors[] = ['msg' => '请勿重复提交'];
                    } else {
                        $this->redirect('/user/result');
                    }
                }
            }
            if ($errors) {
                $errors = array_column($errors, 'msg');
            }
        } else {
            //个人认证信息
            $authinfo = $this->model->userAuthInfo($user['club_user_id']);
            $data = [];
            foreach ($authinfo['base'] as $item) {
                $data[$item['item_field']] = (string) $item['item_val'];
            }
            foreach ($authinfo['club'] as $item) {
                $data[$item['item_field']] = (string) $item['item_val'];
            }
            $errors[] = $this->getLanguage()->error('user.system_error');
        }
        $this->model->authitem($authitem);
        $brand = $this->model->get('tb_car_brand', 'id,name', ['deleted' => 0], false);
        $model = $this->model->get('tb_car_model', 'id,name,brand_id', ['deleted' => 0], false);
        $response = new \Windward\Core\Response\Smarty($this->container);
        $response->set('user', $user);
        $response->set('authitem', $authitem);
        $response->set('brand', $brand);
        $response->set('model', $model);
        $response->set('mobile', $mobile);
        $response->set('data', $data);
        $response->set('errors', $errors);
        $response->set('title', '车友认证');
        return $response;
    }

    public function resultAction()
    {
        $response = new \Windward\Core\Response\Smarty($this->container);
        $user = $this->model->getUserByMobile($_SESSION['club_mobile']);
        $response->set('user', $user);
        $host = $this->request->getSchemaHost();
        $url = $host . '/audit/profile?club_user_id=' . $user['id'];
        $tmp = file_get_contents('http://api.t.sina.com.cn/short_url/shorten.json?source=3271760578&url_long=' . urlencode($url));
        $tmp = json_decode($tmp, true);
        if ($tmp[0]['url_short']) {
            $url = $tmp[0]['url_short'];
        }
        $response->set('url', $url);
        $response->set('title', '车友认证');
        return $response;
    }

    /**
     * 个人信息
     */
    public function profileAction()
    {
        //个人微信信息
        $user = $this->model->getUserByMobile($_SESSION['club_mobile']);
        //个人认证信息
        $authinfo = $this->model->userAuthInfo($user['id']);
        $response = new \Windward\Core\Response\Smarty($this->container);
        $response->set('user', $user);
        $response->set('flag', 0);
        $response->set('authinfo', $authinfo);
        $response->set('title', '车友认证');
        return $response;
    }

    /**
     * 该车友会的所有人员列表
     */
    public function wechatUsersAction()
    {
        $sh = $this->request->getQuery('sh');
        $sh['club_id'] = $_SESSION['club_user']['club_id'];
        $sh['auth_status'] = 2;
        $userList = $this->model->clubUserList($sh);
        $response = new \Windward\Core\Response\Smarty($this->container);
        $response->set('userList', $userList);
        $response->setTpl("User/member");
        $response->set('title', '所有成员');
        return $response;
    }

    public function ajaxWechatUsersAction()
    {
        $sh['page'] = $this->request->getPost('page');
        $sh['club_id'] = $_SESSION['club_user']['club_id'];
        $sh['auth_status'] = 2;
        $userList = $this->model->clubUserList($sh);
        echo json_encode($userList);
        die();
    }

    public function errorAction()
    {
        die('params error');
    }

    public function integralAction()
    {
        $response = new \Windward\Core\Response\Smarty($this->container);
        $response->set('user', $_SESSION['club_user']);
        $pointList = $this->model->get('tb_club_user_point', '*', ['club_user_id' => $_SESSION['club_user']['id'], 'deleted' => 0], false);
        $response->set('pointList', $pointList);
        $response->set('title', '积分记录');
        return $response;
    }

    /**
     * 邀请页面
     * @return \Windward\Core\Response\Smarty
     */
    public function invitAction()
    {
        $user = $_SESSION['club_user'];
        if (!$user) {
            $this->redirect('/user/index');
        }
        $club = $this->model->get('tb_club', 'logo', ['id' => $this->club['id'], 'deleted' => 0]);
        $response = new \Windward\Core\Response\Smarty($this->container);
        $host = $this->request->getSchemaHost();
        $invitUrl = $host . '/user/index?referer_id=' . $user['id'];
        $tmp = file_get_contents('http://api.t.sina.com.cn/short_url/shorten.json?source=3271760578&url_long=' . urlencode($invitUrl));
        $tmp = json_decode($tmp, true);
        if ($tmp[0]['url_short']) {
            $invitUrl = $tmp[0]['url_short'];
        }
        $response->set('user', $user);
        $response->set('club', $club);
        $response->set('url', $invitUrl);
        $response->set('title', '邀请车友');
        return $response;
    }

    /**
     * 显示邀请二维码
     */
    public function shareImgAction()
    {
        $refererId = $this->request->getQuery('referer_id');
        $host = $this->request->getSchemaHost();
        $invitUrl = $host . '/user/index?referer_id=' . $refererId;
        include_once APP . '/Extend/Qrcode.php';
        $qrcode = new \QRcode();
        $qrcode->png($invitUrl, false, QR_ECLEVEL_L, 10, 1);
    }

    public function mobileLoginAction()
    {
        $errors = [];
        $response = new \Windward\Core\Response\Smarty($this->container);
        if ($this->request->isComplete()) {
            $data = $this->request->getPost('data');
            if ($this->model->validMobile($data, $errors)) {
                $aes = new \Windward\Lib\Aes();
                $mobile = $aes->encrypt($data['mobile'], $this->codeConfig['aesKey'], $this->codeConfig['aesIv']);
                setcookie('user_mobile_' . $this->club['id'], $mobile, time() + 3600 * 24 * 365, '/');
                $this->redirect('/user/index');
            }
            $response->set('data', $data);
        }
        if ($errors) {
            $errors = array_column($errors, 'msg');
        }
        $response->set('errors', $errors);
        return $response;
    }

    public function pointRuleAction()
    {
        $response = new \Windward\Core\Response\Smarty($this->container);
        $response->set('title','积分规则');
        return $response;
    }
}
